/*
 * UCRegisterUser.java
 * @author Bian Xiaoguang, Qian Wenshuo
 * Created on 2009-10-25, 18:40:47
 *
 * This use case is to register users into database.
 * Precondition: User enter a invalid username and password .
 * Post-condition: User registers in the system.
 */
package ucm;

import model.UsersModel;
import model.DatabaseModel;
import view.UserRegister;

import javax.swing.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;

public class UCUserRegist implements UCController {

    private UsersModel user;

    public UCUserRegist() {
        user = new UsersModel("", "", "", "", "");
    }

    public UCUserRegist(UsersModel user) {
        // System retrieves username and password
        this.user = user;
    }

    public UCUserRegist(UserRegister registerView) {
        // System retrieves username and password
        this.user = registerView.getUserModel();
    }

    // STEP 1 - User Selects Register
    public boolean run() {
        boolean registeredSuccessful = false;
        // STEP 2 - System retrieves username and password
        // This step is integrated into the constructor or
        // may be specified by using run(UserModel)
        // STEP 3 - System checks username and password are valid (greater than 4 characters)
        if (validDetails()) {
            //Step 4 - System checks with database that username is unique
            if (uniqueUser()){
                //Step 5 - System registers username and password with database
                if (registerUser()) {
                    // STEP 6 - System displays 'Registered Successfully' message
                    JOptionPane.showMessageDialog(new JFrame(),
                            "Registered Successfully!",
                            "Success",
                            JOptionPane.INFORMATION_MESSAGE);
                      new ucm.UCDispalyUserLogin();
                    registeredSuccessful = true;
                } else {
                    JOptionPane.showMessageDialog(new JFrame(),
                            "Registration failed for unknown reason",
                            "Error Message",
                            JOptionPane.ERROR_MESSAGE);
                }
            } else {
                //Step 4a - System displays 'username not unique' message
                JOptionPane.showMessageDialog(new JFrame(),
                        "Username already exists, please choose another",
                        "Error Message",
                        JOptionPane.ERROR_MESSAGE);
            }
        } else {
            //Step 3a - System displays 'invalid user details' message
            JOptionPane.showMessageDialog(new JFrame(),
                    "Username or password invalid (must be between 5 and 10 characters)",
                    "Error Message",
                    JOptionPane.ERROR_MESSAGE);
        }
        return registeredSuccessful;
    }

    // STEP 1 - User Selects Register
    public void run(UsersModel user) {
        // STEP 2 - System retrieves username and password
        this.user = user;
        // STEP 3 onwards
        run();
    }

    private boolean validDetails() {
        // Check the length of the username and password
        return (user.getUsername().length() >= 4) &&
                (user.getUsername().length() <= 16) &&
                (user.getPassword().length() >= 4) &&
                (user.getPassword().length() <= 16);
    }

    private boolean uniqueUser() {
        boolean unique = false;
        String username = user.getUsername();

        Connection con = DatabaseModel.getInstance().getConnection();

        try {
            Statement stmt = con.createStatement(ResultSet.CONCUR_UPDATABLE,
                    ResultSet.CONCUR_UPDATABLE);

            ResultSet res = stmt.executeQuery("SELECT * FROM users WHERE " +
                    "uname = '" + username + "'");

            unique = !(res.first() && username.equals(res.getString("uname")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unique;

    }

    private boolean registerUser(){
        boolean register = false;
        String username = user.getUsername();
        String password = user.getPassword();
        String phone = user.getPhone();
        String email = user.getemail();

        DatabaseModel dbModel = DatabaseModel.getInstance();

        Connection con = dbModel.getConnection();
        try {
            Statement stmt = con.createStatement(ResultSet.CONCUR_UPDATABLE,
                    ResultSet.CONCUR_UPDATABLE);

            stmt.executeUpdate("INSERT INTO users (`UNAME`, `UPASSWORD`, `UPHONE`, `UEMAIL`) values('" + username + "', '" + password + "', " + phone + ", '" + email + "')");
            register = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return register;
    }
}